package com.hdx.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.hdx.common.constant.MessageConstant;
import com.hdx.common.context.BaseContext;
import com.hdx.common.exception.AddressBookBusinessException;
import com.hdx.common.exception.OrderBusinessException;
import com.hdx.common.result.PageResult;
import com.hdx.common.utils.WeChatPayUtil;
import com.hdx.model.dto.*;
import com.hdx.model.entity.*;
import com.hdx.model.vo.OrderPaymentVO;
import com.hdx.model.vo.OrderStatisticsVO;
import com.hdx.model.vo.OrderSubmitVO;
import com.hdx.model.vo.OrderVO;
import com.hdx.server.mapper.*;
import com.hdx.server.service.OrderService;
import com.hdx.server.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    // 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
    // 支付状态 0未支付 1已支付 2退款



    //订单搜索
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //Pagehelper
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //Page
        Page<Orders> page=orderMapper.pageQuery(ordersPageQueryDTO);
        //私有方法getOrderVOList(将orderlist转成orderVOList(私有方法getOrderDishesStr根据订单id获取菜品信息字符串))
        List<OrderVO> orderVOList=getOrderVOList(page.getResult());
        //PageResult(total,orderVOLit)
        return new PageResult(page.getTotal(),orderVOList);
    }

    private List<OrderVO> getOrderVOList(List<Orders> ordersList) {
        ArrayList<OrderVO> orderVOList = new ArrayList<>();
        for(Orders orders:ordersList){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            //私有方法,显示所以菜名*num
            String orderDishes=getOrderDishesStr(orders);
            orderVO.setOrderDishes(orderDishes);
            orderVOList.add(orderVO);
        }
        return orderVOList;
    }
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    //各个状态的订单数量统计（statistics统计）
    @Override
    public OrderStatisticsVO getStatistics() {
        //根据状态，分别查询出待接单、待派送、派送中的订单数量 234
        Integer tobeConfirmedCount =orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmedCount =orderMapper.countStatus(Orders.CONFIRMED);
        Integer DeliveryInProgressCount =orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        //封装返回statisticsVO
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待接单,已接单,配送中
        orderStatisticsVO.setToBeConfirmed(tobeConfirmedCount);
        orderStatisticsVO.setConfirmed(confirmedCount);
        orderStatisticsVO.setDeliveryInProgress(DeliveryInProgressCount);
        return orderStatisticsVO;
    }
    //查询订单详情
    @Override
    public OrderVO getOrderVOById(Long id) {
        Orders orders=orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);

        Long orderId = orders.getId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);

        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }
    //接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //build(id和状态)
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }
    ///拒单
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //根据id查询订单,订单只有存在且状态为2（待接单）才可以拒单
        Long orderId = ordersRejectionDTO.getId();
        Orders ordersDB=orderMapper.getById(orderId);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    //取消订单
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    //派送订单
    @Override
    public void delivery(Long id) {
    //根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
    //校验订单是否存在，并且状态为3
        if (ordersDB == null && !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    //更新订单状态,状态转为派送中
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);

    }
    //完成订单
    @Override
    public void complete(Long id) {
        //根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        //校验订单是否存在，并且状态为4
        if (ordersDB == null && !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //更新订单状态,状态转为已完成
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);

        orderMapper.update(orders);
    }
    //用户下单
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //根据addressBookId查询地址为空,抛出异常,线程获取userId,根据userId查询购物车,购物车为空,抛出异常
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook=addressBookMapper.getById(addressBookId);
        if(addressBook==null){
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
//        Long userId = BaseContext.getCurrentId();
        Long userId = 1L;
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        //封装orders
        //2. 向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        orderMapper.insert(orders);

        //建立orderDetailList集合,遍历购物车,建立orderDetalil对象,将cart属性赋值orderDetail,设置orderId,批量插入数据库orderDetailList
        List<OrderDetail> orderDetailList =new ArrayList<>();
        for(ShoppingCart cart:shoppingCartList){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }
        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装返回orderSubmitVO
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setId(orders.getId());
        return orderSubmitVO;
    }

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    @Override
    public void userCancelById(Long id) throws Exception {
        Orders ordersDB = orderMapper.getById(id);
        if(ordersDB==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(id);

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setCancelReason("用户取消订单");
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);



    }

    @Override
    public void repetition(Long id) {

            // 查询当前用户id
            Long userId = BaseContext.getCurrentId();

            // 根据订单id查询当前订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

            // 将订单详情对象转换为购物车对象
            List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
                ShoppingCart shoppingCart = new ShoppingCart();

                // 将原订单详情里面的菜品信息重新复制到购物车对象中
                BeanUtils.copyProperties(x, shoppingCart, "id");
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(LocalDateTime.now());

                return shoppingCart;
            }).collect(Collectors.toList());

            // 将购物车对象批量添加到数据库
            shoppingCartMapper.insertBatch(shoppingCartList);
        }


    @Override
    public void reminder(Long id) {
       // 客户催单
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type",2); //1表示来单提醒 2表示客户催单
        map.put("orderId",id);
        map.put("content","订单号：" + ordersDB.getNumber());

        //通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public void paySuccess(String outTradeNo) {

    }
}



            //订单支付
    //
    //历史订单查询
//PageHelper
//新建对象OrderPageQueryDto,通过线程获取userId,设置状态,分页查询获取page
//新建OrderVO集合,
//如果page不等于空切page的总条数大于0,遍历page集合的orders,获取orderId,根据orderId查询订单明细列表,新建orderVO,orders属性拷贝orderVO,orderVO设置详细列表,orderVO加入page
//return new PageResult(page.getTotal(), list);

           // 查询订单详情
// 根据id查询订单
//查询该订单对应的菜品/套餐明细
//封装返回orderVO

    //取消订单
//根据id查询订单,订单不存在抛出异常
//如果订单大于2抛出异常不可以取消
//处于待接单需要调用微信接口refund进行退款
//新建订单orders,设置订单id,订单状态为取消,取消原因,取消时间,更新orders

           // 再来一单
//通过线程获取userId,通过id查询订单详细列表,
//stream.map将订单列表转为购物车列表(建立购物车对象,订单详细属性拷贝购物车,忽略id,购物车设置用户id和创建时间)
//批量插入购物车数据库

    //客户催单
//根据id查询订单,校验订单是否存在,抛出异常
//新建map,放入type为2,orderId为id,content为订单号:+orderDB.getNumber()
//通过websocketServer.sendToAlClient(Json.toJsonString(map)发送











